package lvm.view;


import java.util.HashMap;
import java.util.Map;

import lvm.Contexte;
import lvm.LvmException;
import lvm.reader.Reader;
import lvm.struct.Sexpr;

import org.eclipse.swt.*;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.widgets.*;

public class ContexteView {
	
	private HashMap<Integer, Integer> caretline = new HashMap<Integer, Integer>();
	
	private Text in;
	private Text out;
	
	public ContexteView(Composite s,Display display) {
		
		
		
		Contexte.initContexte();
		Contexte.getContexteCourant().init();
		
		out = new Text(s,SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL);
		in = new Text(s,SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL);
		
		in.setFocus();
	    in.addKeyListener(new KeyAdapter() {
	      public void keyPressed(KeyEvent event) {
	    	
	    	String select;  
	    	int caract_cache;
	    	
	        switch (event.keyCode) {
	        case SWT.CR:
	          out.append(">");
	          
	          //Détection de la ligne a envoyer
	          caract_cache=0;
	          for(Map.Entry<Integer, Integer> e : caretline.entrySet()){
	        	  if(e.getKey()<in.getCaretLineNumber()){
	        		  caract_cache+=e.getValue();
	        	  }
	          }
	          select = in.getText(caract_cache, in.getCaretPosition());
	          if(System.getProperty("os.name").toLowerCase().indexOf("win")>=0)
	          caretline.put(in.getCaretLineNumber(),(in.getCaretPosition()-caract_cache)+2);
	          else if((System.getProperty("os.name").toLowerCase().indexOf("nix")>=0)||(System.getProperty("os.name").toLowerCase().indexOf("nux")>=0))
		      caretline.put(in.getCaretLineNumber(),(in.getCaretPosition()-caract_cache)+1);
	          else {
	        	  try {
					throw new Exception("OS non reconnu");
				} catch (Exception e1) {
					e1.printStackTrace();
					System.exit(0);
				}
	          }
	          
	          //Traitement de la requette
	          try {
	        	  Sexpr s = Reader.read(select);
	        	  out.append(s.eval().toString());
	        	  ContextesVariablesView.srefreshVaraibles(Contexte.getContexteCourant());
				} catch (LvmException e1) {
					out.append(e1.getMessage());
				} catch (NullPointerException e) {
					// TODO: handle exception
				} catch (Exception e2) {
					out.append("system error");
					e2.printStackTrace();
				}
	          
	          out.append("\n");
	          break;
	        }
	      }
	    });
	    
		out.setEditable(false);
		
		
	}
	
	
}
